﻿using Blm.Utils.Extensions;
using System;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Extension;
using VisionCloud.Domain.Repository.Interface.Sys;

namespace VisionCloud.Domain.Repository.Implement.Sys
{
    public class SysRoleRepository : BaseRepository<SysRole>, ISysRoleRepository
    {
        public SysRoleDto FindSysRole(SysRoleDto sysRoleDto)
        {
            return Db.SysRoles.Where(p => p.Name.Contains(sysRoleDto.Name))
                    .Select(w => new SysRoleDto()
                    {
                        RoleId = w.RoleId,
                        Name = w.Name,
                        Description = w.Description,
                        LastUpdatedDate = w.LastUpdatedDate
                    }).SingleOrDefault();
        }

        public async Task<ApiPageResult> GetPage(SysRoleCondition condition)
        {
            var list = await Query()
                .WhereIf(condition.RoleId != Guid.Empty, w => w.RoleId == condition.RoleId)
                .WhereIf(condition.Builtin != null, w => w.Builtin == condition.Builtin)
                .WhereIf(!string.IsNullOrWhiteSpace(condition.Code), w => w.Code == condition.Code)
                .WhereIf(!string.IsNullOrWhiteSpace(condition.Name), w => w.Name.Contains(condition.Name))
                .Where(p => p.IsDeleted == false)
                .Select(w => w.CopyTo<SysRoleDto>())
                .DefaultOrderByDescending(condition, w => w.LastUpdatedDate)
                .ToPageList(condition).ConfigureAwait(false);

            var result = condition.CopyTo<ApiPageResult>();
            result.PageData = list;
            return result;
        }
    }
}